//
//  XGEditViewController.m
//  Instagram
//
//  Created by monkey on 2019/4/21.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <SVProgressHUD/SVProgressHUD.h>
#import <TZImagePickerController/TZImagePickerController.h>

#import "XGEditViewController.h"

@interface XGEditViewController () <TZImagePickerControllerDelegate>

/// 容器视图
@property (nonatomic,strong) UIScrollView *contentView;
/// 头像
@property (nonatomic,strong) UIImageView *userIconImageView;
/// 昵称
@property (nonatomic,strong) UITextField *screenNameTextField;
/// 个人简介
@property (nonatomic,strong) UITextView *descriptionTextView;
/// 性别选择器
@property (nonatomic,strong) UISegmentedControl *genderSegmentedControl;

@end

@implementation XGEditViewController

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    [super loadView];
    
    [self setUpUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setUpNavigationItem];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchViewForHiddenKeyboardAction)];
    [self.view addGestureRecognizer:tap];
    
    // 注册通知 监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 事件监听

/// 隐藏键盘事件
- (void)touchViewForHiddenKeyboardAction
{
    [self.view endEditing:YES];
}

/// 取消按钮事件监听
- (void)cancelButtonAction
{
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

/// 保存按钮事件监听
- (void)saveButtonAction
{
    // 验证字段是否为空
    if (!_screenNameTextField.hasText) {
        [SVProgressHUD showErrorWithStatus:@"请填写完所有字段"];
        return;
    }
    
    // 更新数据
    [XGAccountViewModel currentUser].screenName = _screenNameTextField.text;
    [XGAccountViewModel currentUser].userIcon = [AVFile fileWithData:UIImagePNGRepresentation(_userIconImageView.image) name:@"icon.png"];
    [XGAccountViewModel currentUser].gender = _genderSegmentedControl.selectedSegmentIndex;
    [XGAccountViewModel currentUser].descriptionInfo = _descriptionTextView.hasText ? _descriptionTextView.text : @"这家伙儿很懒,什么也没有写~";
    [[XGAccountViewModel currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (!succeeded) {
            [SVProgressHUD showErrorWithStatus:@"修改失败,请检查网络连接"];
            return;
        }
        
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
         [self cancelButtonAction];
    }];
}

/// 键盘即将显示通知监听
- (void)keyboardWillShowNotification:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _contentView.frame = CGRectMake(_contentView.x, _contentView.y, _contentView.width, _contentView.height - rect.size.height);
}

/// 键盘即将消失通知监听
- (void)keyboardWillHideNotification:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _contentView.frame = CGRectMake(_contentView.x, _contentView.y, _contentView.width, _contentView.height + rect.size.height);
}

/// 从相册选择照片
- (void)pickerImageFromPhotosAction
{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - 其他方法

/// 设置导航栏
- (void)setUpNavigationItem
{
    self.navigationItem.title = @"编辑";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveButtonAction)];
}

/// 设置界面
- (void)setUpUI
{
    [self.view addSubview:self.contentView];
    
    // 添加容器视图
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    CGFloat navigationBarHeight = statusBarHeight + 44.f;
    CGFloat bottomMargin = statusBarHeight > 20 ? 34 : 0;
    // 布局容器视图
    _contentView.frame = CGRectMake(0, navigationBarHeight, self.view.width, self.view.height - navigationBarHeight - bottomMargin);
    _contentView.contentSize = _contentView.size;
    
    // 容器视图添加子控件
    [_contentView addSubview:self.userIconImageView];
    [_contentView addSubview:self.screenNameTextField];
    [_contentView addSubview:self.descriptionTextView];
    [_contentView addSubview:self.genderSegmentedControl];
    
    // 容器视图布局子控件
    _userIconImageView.frame = CGRectMake((_contentView.width - 80) / 2, 30, 80, 80);
    _userIconImageView.layer.cornerRadius = _userIconImageView.width / 2.f;
    _userIconImageView.layer.masksToBounds = YES;
    
    CGFloat textFieldHeight = 36;
    _screenNameTextField.frame = CGRectMake(20, _userIconImageView.maxY + 15, _contentView.width - 40, textFieldHeight);
    _descriptionTextView.frame = CGRectMake(20, _screenNameTextField.maxY + 15,  _contentView.width - 40 , 200);
    _genderSegmentedControl.frame = CGRectMake(20, _descriptionTextView.maxY + 15, 80, 36);
}

#pragma mark - 代理

/// 从相册取回图片代理
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    _userIconImageView.image = photos.firstObject;;
}

#pragma mark - 懒加载

- (UIScrollView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIScrollView alloc] init];
        _contentView.backgroundColor = [UIColor red:210 green:254 blue:91 alpha:1];
        _contentView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    return _contentView;
}

- (UIImageView *)userIconImageView
{
    if (!_userIconImageView) {
        _userIconImageView = [[UIImageView alloc] init];
        _userIconImageView.userInteractionEnabled = YES;
        [_userIconImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerImageFromPhotosAction)]];
        [[XGAccountViewModel currentUser].userIcon downloadWithCompletionHandler:^(NSURL * _Nullable filePath, NSError * _Nullable error) {
            UIImage *image = [UIImage imageWithContentsOfFile:filePath.path];
            self->_userIconImageView.image = image;
        }];
    }
    
    return _userIconImageView;
}

- (UITextField *)screenNameTextField
{
    if (!_screenNameTextField) {
        _screenNameTextField = [UITextField textFieldWithPlaceholder:@"昵称(必填)" fontSize:15 textColor:[UIColor darkTextColor] isSecureTextEntry:NO keyboardType:UIKeyboardTypeDefault];
        _screenNameTextField.text = [XGAccountViewModel currentUser].screenName;
    }
    
    return _screenNameTextField;
}

- (UISegmentedControl *)genderSegmentedControl
{
    if (!_genderSegmentedControl) {
        _genderSegmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"男",@"女"]];
        _genderSegmentedControl.selectedSegmentIndex = [XGAccountViewModel currentUser].gender;
        [_genderSegmentedControl sizeToFit];
    }
    
    return _genderSegmentedControl;
}

- (UITextView *)descriptionTextView
{
    if (!_descriptionTextView) {
        _descriptionTextView = [[UITextView alloc] init];
        _descriptionTextView.font = [UIFont systemFontOfSize:15];
        [_descriptionTextView setPlaceholderWithText:@"个人简介(非必填)" Color:[UIColor lightGrayColor]];
        _descriptionTextView.text = [XGAccountViewModel currentUser].descriptionInfo;
        
    }
    
    return _descriptionTextView;
}

@end
